import { Component, OnInit } from '@angular/core';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-popup',
  template: `
    <br>
    <div cdkDrag cdkDragBoundary="body" class="option-panel" (cdkDragEnded)="flag=true">

      <ng-container *ngFor="let item of options; let idx = index">
        <div (click)="clickOption(idx)" class="option-panel-font"
             (mouseenter)="mouseenter(item)" (mouseleave)="mouseleave(item)"
             [@hoverAnimation]="item.isHover ? 'hover' : 'normal'" @slideIn>{{item.name}}</div>
      </ng-container>

    </div>
  `,
  styleUrls: ['./popup.component.scss'],
  animations: [
    trigger('hoverAnimation', [
      state('hover', style({
        marginLeft: '-10px',
        marginRight: '-10px',
      })),
      transition('normal => hover', [
        animate('0.15s'),
      ]),
      transition('hover => normal', [
        animate('0.3s'),
      ]),
    ]),
    trigger('slideIn', [
      transition(':enter', [
        style({opacity: 0, transform: 'translateX(-40px)'}),
        animate(300, style({opacity: 1, transform: 'translateX(0)'})),
      ]),
      transition(':leave', [
        animate(300, style({opacity: 0, transform: 'translateX(100%)'})),
      ]),
    ]),
  ],
})
export class PopupComponent implements OnInit {
  options: any[] = [
    {name: 'Option'},
    {name: 'Option'},
  ];
  flag = false;

  constructor(
      private addSubject$: Observable<any>,
  ) {
    this.addSubject$.subscribe(r => {
      if (r === 'add') {
        this.add();
      }
    });
  }

  ngOnInit(): void {
  }

  clickOption(idx: number) {
    if (this.flag) {
      this.flag = false;
      return;
    }
    this.options.splice(idx, 1);
  }

  mouseenter(item: any) {
    item.isHover = true;
  }

  mouseleave(item: any) {
    item.isHover = false;
  }

  add() {
    this.options.push({name: 'Option'});
  }
}
